package com.iteaj.iot.codec.filter;

import com.iteaj.iot.FrameworkComponent;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.util.ReferenceCounted;

/**
 * 解码拦截器
 */
public interface DecoderInterceptor<C extends FrameworkComponent> extends Interceptor<C> {

    DecoderInterceptor DEFAULT = new DecoderInterceptor(){};

    /**
     * 客户端空闲状态的处理
     * @param deviceSn
     * @param state
     * @return 返回{@code state}将直接关闭连接, 返回{@code null}不处理, 返回{@code Message} or {@code Protocol}直接写出
     */
    default Object idle(String deviceSn, IdleState state) {
        return state;
    }

    /**
     * 此连接是否可激活
     * @see ChannelInboundHandler#channelActive(ChannelHandlerContext)
     * @param channel
     * @param component
     * @return true：允许客户端连接  false：直接关闭连接
     */
    default boolean isActivation(Channel channel, C component) {
        return true;
    }

    /**
     * 是否需要解码
     * @param channel
     * @param msg
     * @return {@code Boolean} 返回true继续解码  false放弃解码  如果要丢弃此报文需要自行处理{@link ReferenceCounted#release()}
     */
    default boolean isDecoder(Channel channel, ReferenceCounted msg) {
        return msg == null ? false : true;
    }
}
